<template>
  <div
    class="device-map"
    v-if="props.mapVisible">
    <div
      class="map-container"
      id="deviceMap"></div>
    <div
      class="back-btn"
      @click="quitMapMode">
      <el-icon><ArrowLeft /></el-icon>
      <div>返回</div>
    </div>
    <div class="left-sidebar">
      <div class="device-table-box">
        <Title titleName="设备地图分布"></Title>
        <div class="device-table">
          <el-table
            :data="deviceMapTableData"
            @row-click="locateDeviceIcon"
            :row-class-name="highlightRowClassName"
            height="100%">
            <el-table-column
              type="index"
              width="80"
              label="序号" />
            <el-table-column
              prop="location"
              label="位置">
              <template #default="{ row }">
                {{ row.result[0].location }}
              </template>
            </el-table-column>
            <el-table-column label="搜索结果总数">
              <template #default="{ row }">
                {{ row.result.length }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <div
      class="info-popup"
      v-if="devicePopupInfo">
      <CardItem
        ref="popupRef"
        :polyFlag="true"
        :isPopup="true"
        :allSelectedFlag="false"
        :cardInfo="devicePopupInfo"
        :searchPkId="props.searchPkId" />
    </div>
  </div>
</template>

<script setup>
  import { getCurrentInstance, ref, reactive, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
  import { ArrowLeft } from '@element-plus/icons-vue'
  import markerIcon from '@/assets/img/page/marker.png'
  import MapInit from '@/utils/mineMap/MapInit'
  import tipMessage from '@/utils/tipMessage'
  import Title from '@/components/title/index.vue'
  import CardItem from './cardItem.vue'
  import { deepClone } from '@/utils/toolUtils'

  const emit = defineEmits(['quitMapMode', 'changeMapVisible'])
  const { proxy } = getCurrentInstance()
  const props = defineProps({
    mapVisible: {
      type: Boolean,
      default: false
    },
    deviceMapData: {
      type: Array,
      default: []
    },
    searchPkId: {
      type: String,
      default: ''
    }
  })
  const deviceMarkerGeoData = ref([])
  const popupRef = ref(null)
  const deviceMapTableData = ref([])
  const devicePopupInfo = ref()
  const highlightedIndex = ref(null)
  const mapObject = {
    darkMapObj: null,
    mapCenter: [],
    marker: null,
    imgInfoPopup: null
  }
  const mapImgsList = [{ src: markerIcon, id: 'markerIcon' }]
  /* ========方法======== */
  const initMap = () => {
    mapObject.darkMapObj = new MapInit('deviceMap', {
      center: [114.88923193324109, 40.76546125305629]
    })
    mapObject.darkMapObj.loadMapImgs(mapImgsList)
    mapObject.darkMapObj.on('load', () => {
      drawDeviceMaker()
    })
    mapObject.darkMapObj.on('click', 'deviceMarkerLayer', viewDeviceDetail)
  }
  const viewDeviceDetail = e => {
    let features = mapObject.darkMapObj.queryRenderedFeatures(e.point, { layers: ['deviceMarkerLayer'] })
    if (features?.length > 0) {
      const { properties } = features[0]
      properties.result = JSON.parse(properties.result)
      devicePopupInfo.value = properties
      nextTick(() => {
        createPopupInfoWindow(devicePopupInfo.value)
      })
    }
  }
  const getMarkerGeoData = () => {
    deviceMarkerGeoData.value = {
      type: 'FeatureCollection',
      features: []
    }
    deviceMarkerGeoData.value.features = deviceMapTableData.value?.map(item => {
      let geoData = {
        type: 'Feature',
        geometry: {
          type: 'Point',
          coordinates: [+item.result[0].lng, +item.result[0].lat]
        },
        properties: item
      }
      return geoData
    })
  }
  const drawDeviceMaker = () => {
    addDeviceMarkerLayerSrc()
    addDeviceMarkerLayer()
  }
  const addDeviceMarkerLayerSrc = () => {
    mapObject.darkMapObj.addSource('deviceMarkerSrc', {
      type: 'geojson',
      data: deviceMarkerGeoData.value,
      generateId: true
    })
  }
  const addDeviceMarkerLayer = () => {
    mapObject.darkMapObj.addLayer({
      id: 'deviceMarkerLayer',
      type: 'symbol',
      source: 'deviceMarkerSrc',
      layout: {
        'icon-image': 'markerIcon',
        'icon-size': 0.5
      }
    })
  }
  const closeInfoWindow = () => {
    if (mapObject.imgInfoPopup) {
      mapObject.imgInfoPopup.remove()
      mapObject.imgInfoPopup = null
    }
  }
  const createPopupInfoWindow = deviceData => {
    closeInfoWindow()
    let center = { lng: +deviceData.result[0].lng, lat: +deviceData.result[0].lat }
    mapObject.imgInfoPopup = new minemap.Popup({
      closeOnClick: false,
      closeButton: false,
      anchor: 'bottom-left',
      offset: [20, 0],
      autoPan: false
    })
      .setLngLat(center)
      .setDOMContent(popupRef.value.cardItemRef)
      .addTo(mapObject.darkMapObj)
    let polyBtn = document.getElementsByClassName('poly-img-btn')
    let closeBtn = document.getElementsByClassName('title-btn')
    closeBtn[0].onclick = () => closeInfoWindow()
    polyBtn[0].onclick = () => {
      let fn = popupRef.value.viewPolyImgList
      fn()
    }
  }
  const locateDeviceIcon = (row, column, event) => {
    devicePopupInfo.value = row
    const index = deviceMapTableData.value.indexOf(row)
    if (highlightedIndex.value === index) {
      highlightedIndex.value = null
      closeInfoWindow()
      return
    } else {
      highlightedIndex.value = index
    }
    let center = [+row.result[0].lng, +row.result[0].lat]
    mapObject.darkMapObj.easeTo(
      {
        center: center,
        zoom: 16.5
      },
      { duration: 1500 }
    )
    nextTick(() => {
      createPopupInfoWindow(devicePopupInfo.value)
    })
  }
  const highlightRowClassName = ({ row, rowIndex }) => {
    return rowIndex === highlightedIndex.value ? 'row-highlight' : ''
  }
  const quitMapMode = () => {
    emit('changeMapVisible', false)
  }
  // 对选择的图片数据按设备类型进一步处理
  const handleSelectPicsData = () => {
    const deviceList = [...new Set(props.deviceMapData.map(item => item.deviceId))]
    if (props.deviceMapData[0].result) {
      // 聚合的数据才有result字段
      deviceList.forEach(device => {
        let tableDataItem = {
          deviceId: device,
          result: []
        }
        props.deviceMapData.forEach(item => {
          if (item.deviceId === device) {
            tableDataItem.result.push(...item.result)
          }
        })
        deviceMapTableData.value.push(tableDataItem)
      })
    } else {
      deviceList.forEach(device => {
        let tableDataItem = {
          deviceId: device,
          result: []
        }
        props.deviceMapData.forEach(item => {
          if (item.deviceId === device) {
            tableDataItem.result.push(item)
          }
        })
        deviceMapTableData.value.push(tableDataItem)
      })
    }
    getMarkerGeoData()
    initMap()
  }
  onMounted(() => {
    handleSelectPicsData()
  })
  onBeforeUnmount(() => {
    if (mapObject.darkMapObj) {
      mapObject.darkMapObj.remove()
    }
  })
</script>

<style scoped lang="scss">
  .device-map {
    position: relative;
    margin: pxTvh(24) 0;
    width: 100%;
    height: calc(100% - #{pxTvh(24)});
    & > .map-container {
      @include wh100();
      :deep .minemap-popup-tip {
        display: none;
      }
      :deep .minemap-popup-content {
        max-width: none !important;
        background-color: transparent;
        padding: 0;
      }
      :deep .card-item {
        width: pxTvw(355);
        height: auto;
        background: rgba(27, 40, 71, 0.85);
        border-radius: 4px;
        z-index: 999999;
      }
    }
    & > .back-btn {
      position: absolute;
      top: pxTvh(24);
      right: pxTvw(24);
      display: flex;
      align-items: center;
      justify-content: center;
      color: #ffffff;
      width: pxTvw(100);
      height: pxTvh(40);
      background: #3153a2;
      border-radius: 4px;
      cursor: pointer;
      z-index: 1500;
      & > div:last-child {
        margin-left: pxTvw(8);
      }
    }
    & > .back-btn:hover {
      background: #456dc9;
    }
    & > .back-btn:active {
      background: #264285;
    }
    & > .left-sidebar {
      width: pxTvw(480);
      backdrop-filter: blur(6px);
      height: 100%;
      padding: 0 pxTvw(16) pxTvh(16) pxTvw(16);
      box-sizing: border-box;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1001;
      background-color: rgba(26, 35, 61, 0.8);
      & > .device-table-box {
        padding: pxTvh(16) 0 0 0;
        overflow: hidden;
        box-sizing: border-box;
        height: 100%;
        & > .device-table {
          height: calc(100% - #{pxTvh(40)});
          overflow: auto;
        }
      }
    }
  }
  .info-popup {
    width: 0;
    height: 0;
    overflow: hidden;
  }
  :deep .row-highlight {
    background-color: #2a49a0;
  }
</style>
